<template>
  <div v-if="visible">
    <el-dialog title="导出" :visible.sync="visible" append-to-body width="555px" :show-close="false">
      <avue-form ref="form" v-model="form" :option="localOption">
        <template slot-scope="{ row }" slot="type">
          <el-radio-group v-model="form.type" @change="handleChange">
            <el-radio label="current" class="custom-radio">当前页面数据</el-radio>
            <el-radio label="all" class="custom-radio">全部数据(当前最大仅支持五百条数据下载)</el-radio>
          </el-radio-group>
        </template>
      </avue-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleExport" size="small" :disabled="loading">导出</el-button>
        <el-button size="small" @click="handleClose">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { excel, calcCascader, loadCascaderDic, loadDic, loadLocalDic, detail } from '@/components/export-excel/util';
import { Message } from 'element-ui';
export default {
  name: 'export-excel',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    loading: {
      type: Boolean,
      default: false
    },
    option: {
      type: Object,
      default: () => ({})
    },
    page: {
      type: Object,
      default: () => ({})
    },
    name: {
      type: String,
      default: ''
    },
    data: {
      type: Array,
      default: () => []
    }
  },

  data() {
    return {
      startPage: 1,
      endPage: 0,
      cascaderDIC: {},
      DIC: {},
      localOption: {
        row: true,
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '文件名',
            prop: 'name',
            span: 24
          },
          {
            label: '选择数据',
            prop: 'type',
            type: 'radio',
            value: 'current',
            span: 24
          },
          {
            label: '选择字段',
            prop: 'prop',
            type: 'tree',
            multiple: true,
            tags: false,
            checkStrictly: true,
            span: 24,
            props: {
              value: 'prop'
            },
            dicData:
              this._cloneDeep(this.option).column.filter((item) => {
                item.disabled = false;
                return !item.hide;
              }) || []
          },
          {
            label: '参数设置',
            prop: 'params',
            type: 'checkbox',
            span: 24,
            dicData: [
              {
                label: '表头',
                disabled: true,
                value: 'header'
              },
              {
                label: '数据源',
                value: 'data'
              }
              // {
              //   label: '复杂表头',
              //   value: ''
              // },
              // {
              //   label: '合计统计',
              //   value: ''
              // }
            ],
            value: ['header', 'data']
          }
        ]
      },
      columnOption: [],
      form: {
        name: this.name,
        type: 'current'
      }
    };
  },
  computed: {
    isDisabled() {
      return this.form.data !== 'custom';
    },
    propOption() {
      let result = [];
      function findProp(list = []) {
        if (!Array.isArray(list)) return;
        list.forEach((ele) => {
          if (Array.isArray(ele.children)) findProp(ele.children);
          else result.push(ele);
        });
      }
      findProp(this.columnOption);
      result = calcCascader(result);
      return result;
    },
    resultOption() {
      return Object.assign(this._cloneDeep(this.option), {
        column: this.propOption
      });
    }
  },
  mounted() {
    this.getColumnOption();
    this.dicInit();
  },
  methods: {
    handleExport() {
      try {
        excel({
          title: this.form.name,
          columns: this.getColumn(),
          data: this.handleSum()
        });
      } catch (e) {
        Message({
          message: '请联系管理员',
          type: 'error'
        });
        console.log(e);
      }
      this.$emit('close', 'current');
      this.form.type = 'current';
    },
    handleClose() {
      this.form.type = 'current';
      this.$emit('close', 'current');
    },
    dicInit(type) {
      if (type === 'cascader') {
        this.handleLoadCascaderDic();
      } else {
        this.handleLoadDic();
      }
    },
    getColumnOption() {
      let column = this._cloneDeep(this.option).column || [];
      let prop = [];
      const findProp = (list = []) => {
        list.forEach((ele, index) => {
          let children = ele.children;
          if (children && !Array.isArray(children)) delete ele.children;
          else if (ele.showColumn === false) list.splice(index, 1);
          else {
            prop.push(ele.prop);
            if (ele.children) findProp(children);
          }
        });
      };
      findProp(column);
      this.columnOption = column;
      this.$set(this.form, 'prop', prop);
    },
    // 获取导出的列
    getColumn() {
      let columns = this._cloneDeep(this.columnOption);
      let props = this.$refs.form.getPropRef('prop').$refs.temp.getHalfList();
      if (!this.form.params) return [];
      if (this.form.params.includes('headers')) {
        const findProp = (list = []) => {
          list.forEach((ele, index) => {
            if (!props.includes(ele.prop)) {
              list.splice(index, 1);
            } else if (ele.children) {
              findProp(ele.children);
            }
          });
        };
        findProp(columns);
        return columns;
      } else {
        let result = [];
        const findProp = (list = []) => {
          list.forEach((ele, index) => {
            if (ele.children) {
              findProp(ele.children);
            } else if (props.includes(ele.prop) || ele.level) {
              result.push(ele);
            }
          });
        };
        findProp(columns);
        return result.filter((item) => !item.hide || item.level);
      }
    },
    //计算统计
    handleSum() {
      const option = this.option;
      const columnOption = this.propOption;
      let list = this.data;
      let data = [];
      if (this.form.params.includes('data')) {
        list.forEach((ele) => {
          let obj = this.deepClone(ele);
          columnOption.forEach((column) => {
            let DIC = column.parentProp ? (this.cascaderDIC[row.$index] || {})[column.prop] : this.DIC[column.prop];
            obj[column.prop] = detail(obj, column, option, DIC);
            if (column['dicUrl'] || column['dicData']) {
              if (!column.formatter || !typeof column.formatter === 'function') {
                obj[column.prop] = obj[`$${column.prop}`];
              }
            }
          });
          data.push(obj);
        });
      }
      // 统计合计
      // if (this.form.params.includes('sum') && option.showSummary) {
      //   data.push(this.crud.sumsList);
      // }
      return data;
    },
    //获取导出的数据
    getData() {},
    //选择开始的页码
    handleSelectStartPage() {},
    //选择结束的页码
    handleSelectEndPage() {},
    //本地字典
    handleLocalDic() {
      loadLocalDic(this.resultOption, this);
    },
    handleChange(val) {
      this.$emit('selectData', val);
    },
    // 网络字典加载
    handleLoadDic() {
      loadDic(this.resultOption, this);
    },
    //级联字典加载
    handleLoadCascaderDic() {
      loadCascaderDic(this.propOption, this);
    }
  }
};
</script>
<style lang="scss">
.custom-radio {
  width: 100%;
  height: 40px;
  line-height: 30px;
}
.pages-select {
  display: inline-block;
  .number-input {
    width: 100px;
  }
}
</style>
